package karileet.meeting.profile.provider;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.RemoteViews;
import karileet.meeting.profile.MeetingProfile;
import karileet.meeting.profile.ProfileConf;

/**
 * Class for widget button functionality. It also updates button graphics
 * depending on current state (widget is added while app is active)
 * TODO: "no longer needed" error avoiding. Android tends to kill app instance
 * every once in a while
 *
 * @author markus karileet
 */
public abstract class WidgetProvider extends AppWidgetProvider {
    public static String WIDGET_TOGGLE = "Toggle";

    public abstract int getLayout();

    public abstract int getButtonElem();

    public abstract int getSelectedImg();

    public abstract int getNotSelectedImg();

    public abstract Class getCls();

    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        Log.d(ProfileConf.APP, "Received widget onUpdate call");
        for (int appWidgetId : appWidgetIds) {
            Intent intent = new Intent(context, getCls());
            intent.setAction(WIDGET_TOGGLE);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, 0);
            RemoteViews views = new RemoteViews(context.getPackageName(),
                    getLayout());
            views.setOnClickPendingIntent(getButtonElem(), pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
            ProfileConf state = new ProfileConf(context);
            //update button graphics
            if (state.isProfileEnabled()) {
                views.setImageViewResource(getButtonElem(), getSelectedImg());
            } else {
                views.setImageViewResource(getButtonElem(), getNotSelectedImg());
            }
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }


    @Override
    /**
     * @param context Application context
     * @param intent Intent that was fired
     */
    public void onReceive(@NonNull Context context, @NonNull Intent intent) {
        Log.d(ProfileConf.APP, this.getClass().getName() + ": Received widget button press");
        super.onReceive(context, intent);
        if (intent.getAction().equals(WIDGET_TOGGLE)) {
            ProfileConf state = new ProfileConf(context);
            MeetingProfile mp = new MeetingProfile(context);
            if (state.isProfileEnabled()) {
                mp.disable();
            } else {
                mp.enable(true);
            }
            mp.updateWidget();
        }
    }

}
